<?php
/**
 *
 * Author: LiuJianPeng
 * Date: 2023/8/7
 * Time: 14:11
 */

namespace App\OpenApi\AdminApi\Sys;

use App\Model\Core\Sys\SysAreaModel;
use App\Service\OpenApi\AdminApi\OpenBaseApi;
use App\Service\ParamsService;
use App\Service\Core\Sys\Area\SysAreaService;
use App\Service\Core\Sys\Area\SysAreaStoreService;

class SysAreaApi extends OpenBaseApi
{

    /**
     * 获取地区列表
     * @return array
     */
    public function index(): array
    {
        $list = SysAreaService::getInstance()
            ->getListByParentId($this->input('parent_id', 0));
        return alert_info(0, '获取成功', ['list' => $list, 'total' => count($list)]);
    }

    /**
     * 更新OR修改地区信息
     * @return array
     * @throws \Throwable
     */
    public function store(): array
    {
        return (new SysAreaStoreService())
            ->setParentId($this->input('parent_id', 0))
            ->setAreaCode($this->input('area_code'))
            ->setAreaName($this->input('area_name'))
            ->setSimpleSpelling($this->input('simple_spelling'))
            ->setSortCode($this->input('sort_code'))
            ->setStatus($this->input('status'))
            ->setRemark($this->input('remark'))
            ->setOperate($this->operate_id, $this->operate_by)
            ->store($this->input('area_id', 0));
    }

    public function areaTree()
    {
        $sysAreaModel = SysAreaModel::getInstance();
        $area_list = $sysAreaModel->getConnectionTable()
            ->where('status', ParamsService::STATUS_ENABLE)
            ->where('layer', '<=', 2)
            ->get();
        $area_list = obj_to_array($area_list);
        $tree_area_list = [];
        foreach ($area_list as $item) {
            if ($item['parent_id'] == 0) {
                $tree_area_list[] = ['label' => $item['area_name'], 'value' => $item['area_id'], 'parent_id' => $item['parent_id']];
            }
        }
        foreach ($tree_area_list as $key => $item) {
            $children = [];
            foreach ($area_list as $val) {
                if ($val['parent_id'] == $item['value']) {
                    $children[] = ['label' => $val['area_name'], 'value' => $val['area_id'], 'parent_id' => $val['parent_id']];
                }
            }
            $tree_area_list[$key]['children'] = $children;
        }
        return alert_info(0, 'ok', $tree_area_list);
    }
}
